import { createRef } from "react";
import { Navigate, Outlet } from "react-router-dom";
import { SuspenseComponent } from "@/utils/MyFun";
import { getUserMenus } from "@/api/menu";
import * as TYPE from "../action-type";

import LayoutIndex from "@/layout";
import {
  asyncRoutes,
  reactModules,
  getEqualReactModules,
} from "@/router/routes2";
import basicRoutes from "@/router/routes2"; //即routes

const PermissionAction = {
  //后端生成路由，返回的就是最终的路由
  generateRoutesBack() {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await getUserMenus(); //调用接口获取后端传来的路由

        let accessRoutes = buildRoutes(res.data); //处理为前端路由格式

        accessRoutes = accessRoutes.filter((item) => {
          //过滤出没有被隐藏的目录结构
          return item.name && !item.isHidden;
        });
        //更新状态容器中的数据
        resolve({
          type: TYPE.PERMISSION_GENERATEROUTESBACK,
          accessRoutes,
        });
      } catch (error) {
        resolve({
          type: "ERROR",
        });
      }
    });
  },
  //前端控制路由权限，根据角色过滤路由
  generateRoutesFront(role = []) {},
  resetPermission() {
    return {
      type: TYPE.PERMISSION_RESETPERMISSION,
    };
  },
  setCompleteRoutes(action) {
    return {
      type: TYPE.PERMISSION_COMPLETEROUTING,
      routes: action.routes,
    };
  },
};
// * 后端路由相关函数
// 根据后端传来数据构建出前端路由
function buildRoutes(routes = []) {
  let formatRoutes = []; //格式化后的路由
  let temp_route = {};

  routes.forEach((route, index) => {
    //处理一级路由情况
    if (["首页", "个人中心", "测试"].includes(route.name)) {
      //无二级菜单情况(这么写死暂时没有想到别的方法，因为菜单的一级情况估计只有几个暂时写死)
      temp_route = {
        name: route.name,
        path: route.path,
        isHidden: route.hidden,
        nodeRef: createRef(null),
        element: SuspenseComponent(`${route.component}`), //统一存放子路由位置
        meta: {
          title: route.children[0].name,
          icon: route.children[0].icon,
          order: route.children[0].order_num,
          keepAlive: route.children[0].keep_alive,
        },
      };
    } else {
      temp_route = {
        name: route.name,
        path: route.component !== "Layout" ? "/" : route.path,
        isHidden: route.hidden,
        nodeRef: createRef(null),
        redirect: route.redirect,
        element: <Outlet />, //统一存放子路由位置
        meta: {
          title: route.name,
          icon: route.icon,
          order: route.order_num,
          keepAlive: route.keep_alive,
        },
        children: buildRoutesChild(route),
      };
    }
    formatRoutes.push(temp_route);
  });

  return formatRoutes;

  /*   return routes.map((e) => ({
    name: e.name,
    path: e.component !== "Layout" ? "/" : e.path, // 处理目录是一级菜单的情况
    component: <LayoutIndex />,
    isHidden: e.hidden,
    redirect: e.redirect,
    meta: {
      title: e.name,
      icon: e.icon,
      order: e.order_num,
      keepAlive: e.keep_alive,
    },
    children: e.children.map((ee) => ({
      name: ee.name,
      path: ee.path, // 父路径 + 当前菜单路径
      // ! 读取动态加载的路由模块
      component: getEqualReactModules(`/src/views${ee.component}/index.jsx`),
      isHidden: ee.hidden,
      meta: {
        title: ee.name,
        icon: ee.icon,
        order: ee.order_num,
        keepAlive: ee.keep_alive,
      },
    })),
  })); */
}

function buildRoutesChild(route) {
  /* 
      首页没有redirect属性 注意！！!需要自己处理
      // 
    */
  if (route.redirect) {
    route.children.unshift({
      path: route.component !== "Layout" ? "/" : route.path,
      nodeRef: createRef(null),
      element: <Navigate to={route.redirect} />,
      hasmodified: true, //代表已经修改过了，因为是先插入到route数组中，后进行遍历修改，所以重定向的部分可以不进行格式化处理
      redirect: true,
    });
  }

  return route.children.map((ee) => {
    if (ee.hasmodified) return ee; //重定向部分
    return {
      name: ee.name,
      path: ee.path, // 父路径 + 当前菜单路径
      // ! 读取动态加载的路由模块
      element: SuspenseComponent(`${ee.component}`),
      isHidden: ee.hidden,
      nodeRef: createRef(null),
      meta: {
        title: ee.name,
        icon: ee.icon,
        order: ee.order_num,
        keepAlive: ee.keep_alive,
      },
    };
  });
}

export default PermissionAction;
